package com.fzt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzt.reggie.common.R;
import com.fzt.reggie.entity.User;
import com.fzt.reggie.service.UserService;
import com.fzt.reggie.utils.SMSUtils;
import com.fzt.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*
    发送手机验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        //获取手机号
        String phone = user.getPhone();
        if (null != phone){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info(code);
            //调用阿里云服务完成验证码发送
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //需要将验证码保存在Session
            HttpSession session = request.getSession();
            session.setAttribute(phone,code);

            return R.success("短信发送成功");
        }

        return R.error("短信发送失败");
    }

    /*
    登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){

        log.info(map.toString());

        Map map1 = (Map) map.get("phone");
        String phone = (String) map1.get("phone");
        String code = map1.get("code").toString();

        //Object codeInSession = session.getAttribute("code");
        //if (codeInSession != null && codeInSession.equals(code)){
            //登录成功
            //判断是否为新用户，是则完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                //新用户
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }


        //return R.error("登录失败");
    //}
}
